import React, { useState, useEffect } from 'react'
import { Button, Checkbox, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom'
import { debounce } from 'lodash';
import { postList } from '../../api/index'
import jiejia from '../../until/jiejia'
import './user.scss'
export default function User() {

  let navigate = useNavigate()
  const formRef = React.useRef(null);
  const [forms] = Form.useForm();

  const onFinish = debounce((values) => {
    //账号正则,手机号和邮箱
    let arr = /^1[3-9][0-9]{9}$/;
    let str = /^[1-9a-zA-Z][0-9a-zA-Z]{5,17}@[1-9a-zA-Z][0-9a-zA-Z]{1,}\.(com|cn|net)$/;
    //密码验证,密码首字母大写，且长度在1到8位之间，可以包含字母和数字
    let passStr = /^(?=.*[A-Z])[A-Za-z\d]{1,8}$/;
    // let pass=jiejia.set()
    if (arr.test(values.Username) || str.test(values.Username)) {
      if (passStr.test(values.Password)) {
        postList('/user', values).then((res) => {
          console.log(res.data);
          if (res.data.type === 'success') {
            message.open({
              type: 'success',
              content: res.data.message,
            });
            const date = new Date();
            date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000)); // 设置过期时间  
            const expiresStr = `expires=${date.toUTCString()}; path=/`; // 设置cookie的过期时间和路径  
            document.cookie = `${'lpfLongin'}=${JSON.stringify(res.data.data)}; ${expiresStr}`; // 设置cookie的值和过期时间  

            localStorage.setItem(
              "LPFdenglu",
              JSON.stringify({ Username: res.data.data.Username, Password: res.data.data.Password })
            );
            navigate('/home')
          } else if (res.data.type === 'error') {
            message.open({
              type: 'warning',
              content: res.data.message,
            });
            forms.setFieldsValue({
              Password: ''
            })
          } else if (res.data.type === 'info') {
            message.open({
              type: 'warning',
              content: res.data.message,
            });
            forms.setFieldsValue({
              Username: ''
            })
          }
        })
      } else {
        message.open({
          type: 'warning',
          content: '密码格式不对',
        });
        forms.setFieldsValue({
          Password: ''
        })
      }
    } else {
      message.open({
        type: 'warning',
        content: '账号格式不对',
      });
      forms.setFieldsValue({
        Username: ''
      })
    }
  }, 1500);
  const [token, setToken] = useState(null);  
  useEffect(()=>{
    let LpfuseName = localStorage.getItem('LPFdenglu')
   if(LpfuseName){
    setToken(LpfuseName)
   }else{
    navigate('/user')
   }
   return ()=>{
    localStorage.setItem('LpfuseName', token);  
   }
  },[])

  const registerBtn = () => {
    navigate('/register')
    // console.log(111);
  }

  return (
    <div id="userBox">
      <div className="title">
        <h1>FM后台管理系统中台</h1>
      </div>
      <div className="useCont">
        <div className="useHerder">
          <h2>心心相印中台系统</h2>
        </div>
        <div className="useCenter">
          <Form
            name="basic"
            // labelCol={{span: 5,}}
            wrapperCol={{ span: 16, }}
            style={{ Width: 600, }}
            labelAlign="left"
            initialValues={{ remember: true, }}
            onFinish={onFinish}
            ref={formRef}
            form={forms}
          // autoComplete="off"
          >
            <Form.Item
              label="账号"
              name="Username"
              initialValue=''
              rules={[
                {
                  required: true,
                  message: '账号不能为空!',
                },
              ]}
            >
              <Input placeholder='请输入手机号/邮箱号' style={{ width: "300px" }} />
            </Form.Item>

            <Form.Item
              label="密码"
              name="Password"
              initialValue=''
              rules={[
                {
                  required: true,
                  message: '密码不能为空!',
                },
              ]}
            >
              <Input.Password style={{ width: "300px" }} placeholder='请输入密码' />
            </Form.Item>

            <Form.Item
              name="remember"
              valuePropName="checked"
              wrapperCol={{
                offset: 4,
                span: 16,
              }}
            >
              <Checkbox>记住密码</Checkbox>
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 2,
                span: 16,
              }}
            >
              <Button type="primary"
                style={{ width: "300px", marginTop: "30px" }} htmlType="submit">
                登录
              </Button>
            </Form.Item>

            <Form.Item>
              <p style={{ fontSize: '12px' }}>如果没有注册，<i onClick={registerBtn} style={{ color: "blue", cursor: "pointer" }}>请先注册</i></p>
            </Form.Item>
          </Form>
        </div>

      </div>

    </div>
  )
}
